package net.oschina.allchat.message.processing.json;

import java.util.List;

import net.oschina.allchat.message.processing.Attribute;
import net.oschina.allchat.message.processing.BadMessageException;
import net.oschina.allchat.protocol.core.LangText;
import net.oschina.allchat.protocol.core.ProtocolException;
import net.oschina.allchat.protocol.core.stanza.error.BadRequest;

import com.fasterxml.jackson.core.JsonParser;

public final class ParsingUtils {
	private ParsingUtils() {}
	
	public static String processLangTextAttributes(List<Attribute<?>> attributes) {
		if (attributes.size() == 0)
			return null;
		
		if (attributes.size() != 1)
			throw new BadMessageException("only allow one attribute 'allchat:lang' here");
		
		Attribute<?> attribute = attributes.get(0);
		if (attribute.getType() != Attribute.Type.STRING || !LangText.PREFIX_LANG_TEXT.equals(attribute.getPrefix()) ||
				!LangText.LOCAL_NAME_LANG_TEXT.equals(attribute.getLocalName())) {
			throw new BadMessageException(String.format("invalid attribute '%s:%s'",
						attribute.getPrefix(), attribute.getLocalName()));
		}
		
		return attribute.stringValue();
	}
	
	public static BadMessageException newParsingException(JsonParser jsonParser, String info) {
		return new BadMessageException(String.format("%s. offset: %d", info, jsonParser.
				getCurrentLocation().getCharOffset()));
	}
	
	public static ProtocolException newStanzaParsingException(JsonParser jsonParser, String info) {
		return new ProtocolException(new BadRequest(String.format("%s. offset: %d", info, jsonParser.getCurrentLocation().getCharOffset())));
	}
}
